import React, { useState, useRef, RefObject } from "react";
import "./index.css";
import axios from "../../../node_modules/axios/index";
import { log } from "console";
import { fetchEventSource } from "../../../node_modules/@microsoft/fetch-event-source/lib/cjs/fetch";

const Chat: React.FC = () => {
  // 输入内容
  const [inputMessage, setInputMessage] = useState("");
  // 存储和更新答案
  const [responses, setResponses] = useState<{ [question: string]: string[] }>(
    {}
  );
  const myRef: RefObject<HTMLDivElement> = useRef(null);

  const handleSendMessage = async () => {
    // 当输入人物名字超过6个字时，模拟后端返回提示：413 错误
    if (inputMessage.length > 6) {
      alert("Error 413：(输入名字不能超过6个字!) ");
      return;
    }

    // 更新视图
    if (inputMessage) {
      setResponses((prevResponses) => ({
        ...prevResponses,
        [inputMessage]: [],
      }));
    }

    // fetch-event-source: 可通过使用post的方式请求eventSource
    fetchEventSource("/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message: inputMessage,
      }),
      onmessage(ev) {
        const contentText = JSON.parse(ev.data).content;
        if (myRef.current) {
          // 将接收到的数据插入指定容器
          myRef.current.innerText += contentText;
        }
      },
      onclose() {
        console.log("close");
      },
    });

    // 清除输入框
    setInputMessage("");
  };

  return (
    <div>
      <div className="dialog-container ">
        <div>
          {Object.keys(responses).map((question, index) => (
            <div key={index}>
              <div className="question">{question}</div>
              <div className="answer" ref={myRef}></div>
            </div>
          ))}
        </div>
      </div>
      <div className="footer">
        <input
          type="text"
          value={inputMessage}
          onChange={(e) => setInputMessage(e.target.value)}
          className="input"
        />
        <button onClick={handleSendMessage} className="button">
          发送
        </button>
      </div>
    </div>
  );
};

export default Chat;
